import { Message } from "element-ui";
export default {
    /**
     * 从response流中下载文件
     * @param {response} response 
     * @returns 
     */
    downloadFile(response) {
        // 如果返回的blob数据类型是JSON，则进行格式化输出
        if (response.data.type.indexOf("application/json") === 0) {
            const reader = new FileReader()
            reader.addEventListener("loadend", () => {
                // 将会打印json格式
                let obj = reader.result;
                if (obj instanceof ArrayBuffer) {
                    // ArrayBuffer => string
                    const o = String.fromCharCode.apply(null, new Uint8Array(obj))
                    Message.error(JSON.parse(o).message)
                } else {
                    Message.error(JSON.parse(obj).message)
                }
            })
            // 如果转换完中文出现乱码，可以设置一下代码
            reader.readAsText(response.data, "utf-8")
        } else {
            const fileBlob = response.data;
            const fileName = decodeURIComponent(response.headers['excel-name']);
            if (!fileBlob|| !fileName) {
                Message.error("缺失必要的参数: params{fileBytes, fileName}")
                return
            }
            const blob = new Blob([fileBlob], { type: fileBlob.type });
            if (window.navigator.msSaveOrOpenBlob) { // 兼容IE10
                navigator.msSaveBlob(blob, fileName)
            } else {
                const a = document.createElement("a");
                const url = window.URL.createObjectURL(blob);
                a.href = url;
                a.download = fileName;
                a.click();
                window.URL.revokeObjectURL(url);
            }
        }
    },

    /**
     * 
     * 检测是否是移动设备
     * true-是；false-否
     */
    isMobile() {
        return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    }
}
